function formatPage(size, page = false) {
  const count = parseInt(size)
  if (!count && page) {
    return 1
  } else if (!count) {
    return 100
  }
  return count > 0 ? count : Math.abs(count)
}

async function pagination(ctx, next) {
  const formData = ctx.query
  const _limit = formatPage(formData._limit)
  const _page = formatPage(formData._page, true)
  const page = {
    limit: _limit > 10000 ? 10000 : _limit,
    page: _page,
  }

  const sort = {}
  const query = {}
  Object.keys(formData).forEach((item) => {
    if (['_limit', '_page'].includes(item)) {
      return
    }
    const value = formData[item]
    if (item.endsWith('_isNull')) {
      const key = item.split('_')[0]
      query[key] = null
    }
    if (!value) {
      return
    }
    // %key%
    if (item.endsWith('_like')) {
      const key = item.split('_')[0]
      query[key] = new RegExp(value)
      // sort
    } else if (item.endsWith('_sort') && ['1', '-1'].includes(value)) {
      const key = item.split('_')[0]
      sort[key] = value
      // %^key%
    } else if (item.startsWith('startsWith_')) {
      const key = item.split('_')[1]
      query[key] = new RegExp(`^${value}`)
      // key = value
    } else if (item.endsWith('_is')) {
      const key = item.split('_')[0]
      query[key] = value
    }
  })

  ctx.state.page = {
    page: page,
    query: query,
    sort: sort,
  }
  await next()
}

export default pagination
